package com.me.tags;

import com.me.annotation.FieldAttr;

import javax.servlet.ServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.SimpleTagSupport;
import java.io.IOException;
import java.lang.annotation.Annotation;

public class LabelTag extends SimpleTagSupport {
	private String jsp_for;
	private String jsp_class;

	@Override
	public void doTag() throws JspException, IOException {
		PageContext page = ((PageContext) this.getJspContext());
		ServletRequest req = page.getRequest();
		Object model = req.getAttribute("Model");
		JspWriter out = page.getOut();
		try {
			model.getClass().getDeclaredField(jsp_for).getAnnotation(FieldAttr.class).value();
			FieldAttr attr = model.getClass().getDeclaredField(jsp_for).getAnnotation(FieldAttr.class);
			if (attr != null) {
				String displayName = attr.value();
				out.print(
						String.format("<label for='%s' %s>%s</label>",
								jsp_for,
								jsp_class == null ? "" : String.format("class='%s'", jsp_class),
								displayName
						)
				);
			}
		} catch (NoSuchFieldException e) {
			e.printStackTrace();
		}
	}

	public void setJsp_for(String jsp_for) {
		this.jsp_for = jsp_for;
	}

	public void setJsp_class(String jsp_class) {
		this.jsp_class = jsp_class;
	}
}
